package com.yanwq.sayhi.controller.user;

import android.content.Intent;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yanwq.sayhi.MApplication;
import com.yanwq.sayhi.common.event.UserEvent;
import com.yanwq.sayhi.common.tool.SharedPrefTool;
import com.yanwq.sayhi.controller.chat.service.ChatService;
import com.yanwq.sayhi.controller.user.activity.LoginActivity;
import com.yanwq.sayhi.dao.bean.User;

import de.greenrobot.event.EventBus;

/**
 * 作者：yanwq。
 * 日期：2016/1/26。
 */
public class UserMgr {
    private static User mUser;

    public static boolean save(JSONObject jsonObject) {
        if (jsonObject == null) {
            return false;
        }

        User user = JSON.parseObject(jsonObject.toJSONString(), User.class);

        if (user == null) {
            return false;
        }

        mUser = user;
        SharedPrefTool.putConfig("user", jsonObject.toJSONString());
        return true;
    }

    public static boolean update(JSONObject jsonObject) {
        if (save(jsonObject)) {
            EventBus.getDefault().post(new UserEvent(UserEvent.UPDATE));
            return true;
        }

        return false;
    }

    public static void delete() {
        mUser = null;
        SharedPrefTool.putConfig("user", null);
    }

    public static User get() {
        if (mUser == null) {
            String userStr = SharedPrefTool.getConfig("user", null);

            mUser = JSON.parseObject(userStr, User.class);

            if (mUser == null) {
                logout();
            }
        }

        return mUser;
    }

    public static void logout() {
        delete();
        Intent intent = new Intent(MApplication.getContext(), LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        MApplication.getContext().startActivity(intent);
        EventBus.getDefault().post(new UserEvent(UserEvent.LOGOUT));
        ChatService.stop();
    }
}
